package com.spzx.common.rabbit.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GmallCorrelationData;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送消息
     *
     * @param exchange
     * @param routingKey
     * @param message
     * @return
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        // 1、创建自定义相关消息对象-包含业务数据本身，交换器名称，路由键，队列类型，延迟时间，重试次数
        GmallCorrelationData correlationData = new GmallCorrelationData();
        String uuid = "mq:" + IdUtil.simpleUUID();
        correlationData.setId(uuid);
        correlationData.setMessage(message);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        // 2、将相关消息封装发送到消息方法中
        rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationData);
        // 3、将相关消息存入Redis，key:uuid 相关消息对象 10分钟
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData), 10, TimeUnit.MINUTES);
        return true;
    }
}
